//
//  LoginViewController.m
//  NPS
//
//  Created by jadd on 15/10/14.
//  Copyright © 2015年 jadd. All rights reserved.
//

#import "LoginViewController.h"

#define fitScreenHeight (K_ScreenHeight/568)

@implementation LoginViewController
@synthesize userName,userPwd;
@synthesize isKeyBoardShowed;


//立即注册
-(IBAction)askAccountAction:(id)sender
{
    RegisterController *controller = [[RegisterController alloc] initWithStyle:UITableViewStyleGrouped];
    //[self.navigationController pushViewController:controller animated:YES];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
    controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:nav animated:YES completion:^{
        NSLog(@"");
    }];
}

//登陆事件
-(IBAction)loginAction:(id)sender{
    NSString *name = [self.userName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *pwd = [self.userPwd.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([name isEqualToString:@""]){
        [Config showMessage:@"用户名不能为空！"];
    }else if([pwd isEqualToString:@""]) {
        [Config showMessage:@"密码不能为空！"];
    }else{
        [Config showActivityView];
        LoginRequest * request = [[LoginRequest alloc] initWithUserName:name
                                                               password:pwd];
   
        [RequestHandle startOperationWithRequest:request
                                        complete:^(id responseObject) {
                                            
                                            LoginResponse * response = [[LoginResponse alloc] init];
                                            response.responseObject = responseObject; //保存登陆数据
                                          
                                            //[GMDCircleLoader hideFromView:self.view animated:YES];
                                            while (![[NSUserDefaults standardUserDefaults] synchronize]) {}
                                            //登陆成功
                                            [Config hideActivityView];
                                             
                                            [self clearTextField];
//                                            StoresInfoController *controller = [[StoresInfoController alloc] init];
//                                            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
//                                            controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
//                                            [self presentViewController:nav animated:YES completion:^{
//                                                NSLog(@"");
//                                            }];
                                           
                                            StoresInfoController *controller = [[StoresInfoController alloc] init];
                                            [self.navigationController pushViewController:controller animated:YES];
                                            
                                        } error:^(NSError *error) {
                                            
                                           
                                            //[Config hideActivityView];
                                            [Config showMessage:error.localizedDescription];
                                            
                                        }];

    }
    

}

-(IBAction)forgetAction:(id)sender
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                    message:@"是否拨打客服找回密码？"
                                                   delegate:self
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"呼叫",nil];
    alert.tag = 1;
    [alert show];
        
    
}

#pragma marks -- UIAlertViewDelegate --
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == 1 && buttonIndex == 1){
        NSMutableString *call =[[NSMutableString alloc] initWithFormat:@"telprompt://%@",@"021-51562435"];
       
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:call]];
    }
}


-(void) setupUi
{
    [self setupBackground];
    //[self setupLoginButton];
    [self setupNavBar];
    [self setupTapGesture];
    
}

-(void) clearTextField
{
    self.userPwd.text = nil;
    
}
-(void) setupBackground
{
    CGRect rect = CGRectMake(0, 0, K_ScreenWidth, K_ScreenHeight);
    
    UIImageView *backImageView = [[UIImageView alloc] initWithFrame:rect];
    backImageView.userInteractionEnabled = YES;
    [backImageView setImage:[UIImage imageNamed:@"bg"]];
 

    UIImageView *logoImgView = [[UIImageView alloc]init];
    logoImgView.contentMode =  UIViewContentModeScaleAspectFit;
    CALayer *layer= [logoImgView layer];
    //是否设置边框以及是否可见
    [layer setMasksToBounds:YES];
    //设置边框圆角的弧度
    [layer setCornerRadius:10.0];
    //设置边框线的宽
    [layer setBorderWidth:0.1];
    logoImgView.userInteractionEnabled = YES;
    [logoImgView setImage:[UIImage imageNamed:@"logobg"]];
    [backImageView addSubview:logoImgView];
    [logoImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(60*fitScreenHeight);
        make.centerX.equalTo(backImageView.mas_centerX);
    }];

    
    UIImageView *ivName = [[UIImageView alloc]init];
    ivName.contentMode =  UIViewContentModeScaleAspectFit;
    [ivName setImage:[UIImage imageNamed:@"font"]];
    [backImageView addSubview:ivName];
    
    //top left bottom right
    [ivName mas_makeConstraints:^(MASConstraintMaker *make) {
        //make.height.equalTo(@150);
        make.top.mas_equalTo(logoImgView.mas_bottom).with.offset(25);
        make.centerX.equalTo(backImageView.mas_centerX);
        
    }];

    ImageButton *accountbtn = [[ImageButton alloc] init];
    [accountbtn setImage:[UIImage imageNamed:@"arrow"] withTitle:@"立即注册" forState:UIControlStateNormal];
   
    accountbtn.titleLabel.font = [UIFont systemFontOfSize:18.0];
    accountbtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    accountbtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    
    [accountbtn setTitleColor:WHITE forState:UIControlStateNormal];
    [accountbtn setTitleColor:GRAY forState:UIControlStateHighlighted];
    

    [accountbtn addTarget:self action:@selector(askAccountAction:) forControlEvents:UIControlEventTouchUpInside];
    [backImageView addSubview:accountbtn];
    [accountbtn  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(fitScreenHeight-20);
        make.left.offset(15);
        make.right.offset(-15);
        make.height.equalTo(@45);
    }];

    
    //登陆
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    //[button setFrame:CGRectMake(25, K_ScreenHeight-(K_ScreenHeight/5), (K_ScreenWidth - 50), 45.0f)];
    [button.layer setMasksToBounds:YES];
    [button.layer setCornerRadius:5.0f];
    [button.layer setBorderWidth:0.5f];
    [button.layer setBorderColor:DEFAULT_LINE_GRAY_COLOR.CGColor];
    button.backgroundColor = [UIColor colorWithHexString:K_Global_ColorHexString_Store];
    
    [button setTitle:@"登  录" forState:UIControlStateNormal];
    UIFont *font = [UIFont systemFontOfSize:20.0];
    [button addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    [button.titleLabel setFont:font];
    [button setTitleColor:WHITE forState:UIControlStateNormal];
    [backImageView addSubview:button];
    [button  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(accountbtn.mas_top).with.offset(-20);
        make.left.offset(15);
        make.right.offset(-15);
        make.height.offset(45);
    }];

    
    UIImageView *imageView = [[UIImageView alloc]init];
    imageView.userInteractionEnabled = YES;
    [imageView setImage:[UIImage imageNamed:@"inputFrame"]];
    [backImageView addSubview:imageView];

    //top left bottom right
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        //make.height.equalTo(@150);
        make.bottom.mas_equalTo(button.mas_top).with.offset(-50);
        make.left.offset(15);
        make.right.offset(-15);
       
    }];

    
    //账号
    UILabel *Account = [[UILabel alloc] init];
    [Account setText:@"用户名"];
    [Account setTextColor:WHITE];
    Account.adjustsFontSizeToFitWidth = YES;
    Account.font = [UIFont boldSystemFontOfSize:18];
    [imageView addSubview:Account];
    
    [Account mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(60, 30));
        make.top.offset(20);
        make.left.offset(10);
    }];

    /*
    UIImageView *nameImageView = [[UIImageView alloc] init];
    [nameImageView setImage:[UIImage imageNamed:@"Phone"]];
    [imageView addSubview:nameImageView];
    [nameImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(30, 30));
        make.top.offset(15);
        make.left.offset(10);
    }];
    */
    
    
    userName = [[UITextField alloc] init];
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserDefault_uName];
    bool hasLogin = (uid == nil || [uid isEqualToString:@""]);
    if(hasLogin == NO)
    {
        userName.text =uid;
    }
    //userName.borderStyle = UITextBorderStyleRoundedRect;
    userName.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
    userName.clearButtonMode = UITextFieldViewModeWhileEditing;
    userName.font = [UIFont systemFontOfSize:18];
    userName.textColor = GRAY;
    //userName.placeholder = @"用户名";
    [imageView addSubview:userName];
    
    [self.userName mas_makeConstraints:^(MASConstraintMaker *make) {
        //make.size.mas_equalTo(CGSizeMake(30, 30));
        make.top.mas_equalTo(Account.mas_top).with.offset(4);
        make.left.mas_equalTo(Account.mas_right).with.offset(15);
        make.right.mas_equalTo(imageView.mas_right).with.offset(-35);
    }];
    

    ////密码
    UILabel *password = [[UILabel alloc] init];
    [password setText:@"密 码"];
    [password setTextColor:WHITE];
    password.adjustsFontSizeToFitWidth = YES;
    password.font = [UIFont boldSystemFontOfSize:18];
    [imageView addSubview:password];
    
    [password mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(60, 30));
        make.left.mas_equalTo(Account.mas_left);
        make.top.mas_equalTo(Account.mas_bottom).with.offset(30);
    }];

    
    /*
    UIImageView *pwdImageView = [[UIImageView alloc] init];
    [pwdImageView setImage:[UIImage imageNamed:@"Password"]];
    [imageView addSubview:pwdImageView];
    [pwdImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(30, 30));
        make.left.mas_equalTo(Account.mas_left);
        make.top.mas_equalTo(Account.mas_bottom).with.offset(15);
    }];
     */
    
    
    self.userPwd = [[UITextField alloc] init];
    //self.userPwd.borderStyle = UITextBorderStyleRoundedRect;
    self.userPwd .clearButtonMode = UITextFieldViewModeWhileEditing;
    self.userPwd.secureTextEntry = YES;
    self.userPwd .font = [UIFont systemFontOfSize:18];
    self.userPwd .textColor = GRAY;
    //self.userPwd .placeholder = @"密码";
    //[self.userPwd setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [imageView addSubview:self.userPwd ];
    //self.userPwd .contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [self.userPwd  mas_makeConstraints:^(MASConstraintMaker *make) {
        //make.size.mas_equalTo(CGSizeMake(30, 30));
        make.top.mas_equalTo(password.mas_top);
        make.left.mas_equalTo(password.mas_right).with.offset(15);
        make.right.mas_equalTo(imageView.mas_right).with.offset(-35);
    }];

    //忘记密码
    UIButton *forgetBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [forgetBtn setTintColor:WHITE];
    //[button setFrame:CGRectMake(25, K_ScreenHeight-(K_ScreenHeight/5), (K_ScreenWidth - 50), 45.0f)];
    [backImageView addSubview:button];
    [forgetBtn setImage:[UIImage imageNamed:@"wangji"] forState:UIControlStateNormal];
    [forgetBtn addTarget:self action:@selector(forgetAction:) forControlEvents:UIControlEventTouchUpInside];
    [forgetBtn.titleLabel setFont:font];
    
    [backImageView addSubview:forgetBtn];
    [forgetBtn  mas_makeConstraints:^(MASConstraintMaker *make) {
        //make.centerY.equalTo(imageView.mas_centerY);
        make.top.mas_equalTo(self.userPwd.mas_top);
        make.left.mas_equalTo(self.userPwd.mas_right).with.offset(10);
        
    }];

    [self.view addSubview:backImageView];//backImageView
}

-(void) setupLoginButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setFrame:CGRectMake(25, K_ScreenHeight-(K_ScreenHeight/5), (K_ScreenWidth - 50), 45.0f)];
 
    [button.layer setMasksToBounds:YES];
    [button.layer setCornerRadius:5.0f];
    [button.layer setBorderWidth:0.5f];
    [button.layer setBorderColor:DEFAULT_LINE_GRAY_COLOR.CGColor];
    button.backgroundColor = [UIColor colorWithHexString:K_Global_ColorHexString_Store];
    
    [button setTitle:@"登  陆" forState:UIControlStateNormal];
    UIFont *font = [UIFont systemFontOfSize:20.0];
    [button addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    [button.titleLabel setFont:font];
    [button setTitleColor:WHITE forState:UIControlStateNormal];
   
    [self.view addSubview:button];
}



-(void) setupNavBar
{
    self.navigationController.navigationBarHidden = true;
    
}

//键盘弹出，将界面上移
-(void) keyBoardWillShowUp: (NSNotification *) notification {
    
    NSDictionary *keyBoardInfo = notification.userInfo;
    
    if(keyBoardInfo != nil){
//      NSDictionary *keyInfo = (NSDictionary *)keyBoardInfo;
//      CGRect rect = [[keyInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.25];
        //CGRectMake(0, 160, K_ScreenWidth, K_ScreenHeight)
        [self.view setBounds:CGRectMake(0, 200, K_ScreenWidth, K_ScreenHeight)];
        
        [UIView commitAnimations];
        isKeyBoardShowed = true;
    }
    
}
 //恢复页面整体上移
-(void) keyBoardWillHide: (NSNotification *) notification {
    
    NSDictionary *keyBoardInfo = notification.userInfo;
    
    if(keyBoardInfo != nil){
//        NSDictionary *keyInfo = (NSDictionary *)keyBoardInfo;
//        CGRect rect = [[keyInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.25];
        
        [self.view setBounds:CGRectMake(0, 0, K_ScreenWidth, K_ScreenHeight)];
        [UIView commitAnimations];
        isKeyBoardShowed = false;
    }
}



//添加手势，收回键盘使用
-(void) setupTapGesture {
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] init];
    [tapGesture addTarget:self action:@selector(pullDownKeyBoard)];
    [self.view addGestureRecognizer:tapGesture];
   
}
//    添加键盘通知方法
-(void) addKeyBoardNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShowUp:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

//移除键盘通知方法
-(void)  removeKeyBoardNotification {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}

-(void) pullDownKeyBoard {
    [userPwd resignFirstResponder];
    [userName resignFirstResponder];
  
}

- (void)viewDidLoad {
    
    [self setupUi];
    [super viewDidLoad];
}

-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addKeyBoardNotification];
    
    [self setupNavBar];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self removeKeyBoardNotification];
    self.navigationController.navigationBarHidden = false;
}

-(void)viewDidDisappear:(BOOL)animated
{
    if(isKeyBoardShowed == true){
        [UIView commitAnimations];
        [self.view setBounds:CGRectMake(0, 0, K_ScreenWidth, K_ScreenHeight)];
    }
    
    //isKeyBoardShowed = false;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
